<?php 

/**
  * Gallery(Control Panel)
  *
  * @author Ian Szewczyk <roamzero@gmail.com>
  * @copyright Ian Szewczyk <roamzero@gmail.com>
  * @license http://www.opensource.org/licenses/gpl-license.php 
  * @package Modules
  * @filesource
  */

require "HTML/QuickForm.php";

/**
  * Gallery (Control Panel)
  *
  * @author Ian Szewczyk <roamzero@gmail.com>
  * @package Modules
  */
class Framework_Module_CP_Gallery extends Framework_Module_CP
{
	private $folders;

	public function __construct()
	{
		parent::__construct();
		$this->presenter = 'None';
		$this->moduleTplFile = 'gallery.tpl';
	}

	public function __default()
	{


		$this->uploadForm();
		$this->folderForm();

	}

	public function uploadForm()
	{
		$this->forms['imageUpload'] = new HTML_QuickForm('imageUpload', 'post', Framework::$site->getUriPath().'/'.$this->owner->remoteUserName.'/CP/Gallery',null,null,true);

		// get folders
		$folders['-1'] = 'root';
		$dbFolders = $this->db->getAssoc('SELECT idFolder, folderName FROM galleryfolder WHERE idOwner='.$this->owner->idOwner);
		if (is_array($dbFolders) && count($dbFolders))
		$folders = $folders + $dbFolders;

		for ($i=1;$i<=4;$i++) {
			$uploadGroup[] = HTML_QuickForm::createElement('file', 'imageFile'.$i, 'Upload Image:');
			$uploadGroup[] = HTML_QuickForm::createElement('select', 'imageFolder'.$i, 'Folder:', $folders);
			$uploadGroup[] = HTML_QuickForm::createElement('text','imageTitle'.$i,'Image Title: ', 'class="textInput" id="imageTitle"');
		}
		$this->forms['imageUpload']->addGroup($uploadGroup, 'uploadImages', 'Upload Images:', ',&nbsp;');

		$this->forms['imageUpload']->addRule('uploadImages', 'Cannot exceed 500KB', 'maxfilesize', 512000);
		$this->forms['imageUpload']->addRule('uploadImages', 'Must be a JPEG or GIF', 'mimetype', array('image/jpeg','image/gif'));

		$this->forms['imageUpload']->addElement('submit','btnSubmitImages','Upload','class="button" id="btnSubmitImages"');

		$this->forms['imageUpload']->applyFilter('__ALL__','trim');

		// Process password change form
		if ($this->forms['imageUpload']->validate()) {
			$result = $this->forms['imageUpload']->process(array($this, 'processUpload'));
		} else {
			$this->forms['imageUpload']->display();
		}


	}

	public function processUpload($data)
	{
		$uploadImages = $this->forms['imageUpload']->getElement('uploadImages');
		$files = $uploadImages->getElements();
		$counter = 1;
		foreach ($files AS $file) {
			if (is_a($file,'HTML_QuickForm_file') && $file->isUploadedFile()) {
				$fileManager = new Framework_File($this->owner);
				$result = $fileManager->addFileUpload($file,'gallery');
				if (PEAR::isError($result)){
					$errors[] = 'Could Not Upload Image';
				} else {
					// TODO: Better file manager
					$fileManager->createthumb($result['fullPath'],dirname($_SERVER['SCRIPT_FILENAME']).'/uploads/thumb/'.$result['hashPath'].$result['fileName'].'.'.$result['ext'],100,100);
					// Get folder ID
					if ($data['uploadImages']['imageFolder'.$counter] != '-1') {
						$folder = $data['uploadImages']['imageFolder'.$counter];
					} else {
						$folder = null;
					}
					$galleryItems[] = array($result['fileID'],$folder,$data['uploadImages']['imageTitle'.$counter] ,time());
				}
				$counter++;
			}

		}
		if ($galleryItems) {
			$sql = 'INSERT INTO galleryitem
      		        (idOwner_File,idFolder,title,date) 
      		        VALUES (?,?,?,?)';
			$stmt = $this->db->prepare($sql);
			$result = $this->db->executeMultiple($stmt, $galleryItems);
			if(PEAR::isError($result)) {
				echo $result->getMessage();
				var_dump($galleryItems);
			}
		}


		return true;
	}

	public function folderForm()
	{

		// First get a listing of the forms
		$sql = 'SELECT * FROM galleryfolder WHERE idOwner ='.$this->owner->idOwner;
		$this->folders = $this->db->getAll($sql);


		// Make the form with save button
		$this->forms['folderForm'] = new HTML_QuickForm('folderForm', 'post', Framework::$site->getUriPath().'/'.$this->owner->remoteUserName.'/CP/Gallery',null,null,true);

		foreach ($this->folders as $folder) {
			$folderGroup[] = HTML_QuickForm::createElement('text','folderName','Folder Name: ', 'size="30" class="textInput" id="folderName"');
			$folderGroup[] = HTML_QuickForm::createElement('submit','folderDelete','Delete','class="button" id="btnDelete"');
			$folderGroup[] = HTML_QuickForm::createElement('select','folderPerm', 'Privacy: ', array('0'=>'Me only','1'=>'Friends only','2'=>'Everyone'));

			$this->forms['folderForm']->addGroup($folderGroup,$folder['idFolder']);

			// Defaults
			$this->forms['folderForm']->setDefaults(array(($folder['idFolder']) => array('folderName'=>$folder['folderName'], 'folderPerm'=>$folder['folderPerm'])));
			$folderGroup = null;
		}

		$this->forms['folderForm']->addElement('text','newFolderName','Folder Name: ', 'size="30" class="textInput" id="newFolderName"');
		$this->forms['folderForm']->addElement('select','newFolderPerm', 'Privacy: ', array('0'=>'Me only','1'=>'Friends only','2'=>'Everyone'));

		$this->forms['folderForm']->addElement('submit','btnUpdateFolders','Update Folders','class="button" id="btnUpdateFolders"');
		$this->forms['folderForm']->addElement('submit','btnSubmitNew','Add Folder','class="button" id="btnSubmitNew"');

		// Filters
		$this->forms['folderForm']->applyFilter('__ALL__','trim');
		$this->forms['folderForm']->applyFilter('__ALL__','htmlentities');

		// Process default module form
		if ($this->forms['folderForm']->validate()) {
			$result = $this->forms['folderForm']->process(array($this, 'processFolder'));
		} else {
			$this->forms['folderForm']->display();
		}
	}

	public function processFolder($data)
	{

		if($data['btnSubmitNew'] && strlen($data['newFolderName']) && strlen($data['newFolderPerm'])) {
			$sql = 'INSERT INTO galleryfolder (idOwner, folderPerm, folderName) VALUES(?,?,?)';
			$stmt = $this->db->prepare($sql);
			$result = $this->db->execute($stmt,array($this->owner->idOwner,$data['newFolderPerm'],$data['newFolderName']));
			if (!PEAR::isError($result)) {
				$this->setData('formResponse','Folder Added!');
			} else {
				$errors[] = 'Error: '.$result->getMessage();
			}
		}

		foreach ($data AS $key=>$value) {
			if (is_array($value)) {
				if ($value['folderDelete']) {
					// Move images to root (root being a null idFolder value)
					$result1 = $this->db->query('UPDATE galleryitem SET idFolder = null WHERE idFolder = ? AND idOwner ='.$this->owner->idOwner,array($key));
					$result2 = $this->db->query('DELETE FROM galleryfolder WHERE idFolder= ? AND idOwner = ?', array($key,$this->owner->idOwner));
					if (PEAR::isError($result1))
						echo $result1->getMessage();
					if (PEAR::isError($result2))
						echo $result2->getMessage();

					// Form Response
					$this->setData('formResponse','Folder Removed!');
				} elseif ($data['btnUpdateFolders'] && strlen($value['folderName'])) {
					// populate update array
					$folderUpdate[] = array($value['folderName'], $value['folderPerm'], $key);
				}
			}
		}

		// If updates..
		if ($folderUpdate) {
			$sql = 'UPDATE galleryfolder SET folderName = ?, folderPerm = ? WHERE idFolder = ? AND idOwner='.$this->owner->idOwner;
			$stmt = $this->db->prepare($sql);
			$result = $this->db->executeMultiple($stmt, $folderUpdate);
			if (!PEAR::isError($result)) {
				$this->setData('formResponse','Folder(s) Edited!');
			} else {
				$errors[] = 'Error: '.$result->getMessage();
			}
		}

		if($errors) {
			$this->setData('errors',$errors);
		}
		var_dump($data);
		$this->presenter = 'Debug';
		return true;

	}

	public function fileManager()
	{
		// Page number
		if ($this->args[1] && preg_match('/^[0-9]+$/',$this->args[1]))
			$pageNumber = $this->args[1];
		else
			$pageNumber = 1;


		// forms
		$this->forms['modify'] = new HTML_QuickForm('modify', 'post', '/'.$this->owner->remoteUserName.'/CP/Gallery/'.$this->args[0].'/'.$pageNumber);

		$this->forms['navigateForm'] = new HTML_QuickForm('navigateForm', 'post', '/'.$this->owner->remoteUserName.'/CP/Gallery/'.$this->args[0].'/'.$pageNumber);

		// Process form
		if ($this->forms['modify']->validate()) {
			$result =$this->forms['modify']->process(array($this, 'move'));

			if (!PEAR::isError($result)) {
				$this->setData('formResponse',$result);
			} else {
				$this->setData('formResponse','Error: Images could not be modified');
			}
		}

		// Folder
		if($this->args[0]) {
			$folder = $this->args[0];
			$countSQL = 'SELECT count(*) AS imageCount FROM galleryitem
		             INNER JOIN galleryfolder ON galleryitem.idFolder = galleryfolder.idFolder
		             WHERE galleryfolder.idFolder = (SELECT idFolder FROM galleryfolder WHERE folderName = ? AND idOwner = ?)';
			$count = $this->db->getOne($countSQL,array($folder,$this->owner->idOwner));
			$selectSQL = 'SELECT * FROM galleryitem INNER JOIN owner_file ON galleryitem.idOwner_File = owner_file.idOwner_File
			              WHERE galleryitem.idFolder = (SELECT idFolder FROM galleryfolder WHERE folderName = ? AND idOwner = ?) AND owner_file.idOwner = ?';
			$params = array($folder,$this->owner->idOwner,$this->owner->idOwner);
		} else {
			$folder = 'root';
			$countSQL = 'SELECT count(*) AS imageCount FROM galleryitem
		             INNER JOIN galleryfolder ON galleryitem.idFolder = galleryfolder.idFolder
		             WHERE galleryfolder.idFolder IS NULL AND idOwner = ?';
			$count = $this->db->getOne($countSQL,array($this->owner->idOwner));
			$selectSQL = 'SELECT * FROM galleryitem INNER JOIN owner_file ON galleryitem.idOwner_File = owner_file.idOwner_File
			              WHERE galleryitem.idFolder IS NULL AND owner_file.idOwner = ?';
			$params = array($this->owner->idOwner);

		}


		$numberToDisplayPerPage = 10;


		if (!$count || PEAR::isError($count)) {
			$this->setData('noResults','No messages to list');
		} else {

			// if a pager is needed make it and set it
			if ($count > $numberToDisplayPerPage) {
				$pager = new Framework_Pager($this->pageNumber,4,$numberToDisplayPerPage,$count,$this->owner->remoteUserName.'/CP/Messages/'.$this->args[0].'/'.$this->args[1]);
				$this->setData('pager',$pager->getNavigation());
			}

			// based on the pagenumber adjust the query limit
			$from = ($numberToDisplayPerPage *($pageNumber)) - $numberToDisplayPerPage ;

			// Get images
			$selectSQL = $selectSQL.' LIMIT '.$from.','.$numberToDisplayPerPage;
			$images = $this->db->getAll($selectSQL,$params);

			if (!PEAR::isError($images)) {
				
				if (is_array($image)) {
				// Generate form elements
				foreach ($images as $image) {
					$imagesToModify[] = HTML_QuickForm::createElement('checkbox',$image['idImage']); 
				}
				$this->forms['modify']->addGroup($imagesToModify,'imagesToModify','Delete or Move: ',' ');
				
				$this->forms['modify']->addElement('submit','btnMove','Move Selected','class="button" id="btnMove"');
				
				// Get the folders
				$friendsList = array("0"=>"Root") + $this->db->getAll('SELECT',array('siteuser.idSiteUser','siteuser.remoteUserName'),null,null,true);
				$this->forms['newMessage']->addElement('select', 'friendsList', 'Choose Friend: ', $friendsList, 'class="listInput" id="friendsList"');
				
				
				$this->forms['modify']->addElement('submit','btnDelete','Delete Selected','class="button" id="btnDelete"');
				
				
				$this->moduleTplFile;


				// READY GO!
				$this->setData('images',$images);
				} else {
					$errors[] = 'Error: No Images Found';
				}
				
				

			} else {
				$errors[] = 'Error: Could not select messages '.$images->getMessage();
			}


		}





	}

	public function modify($data)
	{
		if($data['btnMove']) {
			$sql = 'UPDATE privatemessage SET '.$field[0].' = 0 WHERE idSiteUser_'.$field[1].' = '.$this->owner->idSiteUser.'
			    	AND idPrivateMessage IN'.$in;		
			$result = $this->db->query($sql);
		} elseif ($data['btnDelete']) {
			// get the owner_ids
			$sql = 'something';
			
			// call the file manager and pass the ids to be deleted
			
			
			// upon success, drop images from image table
		}
			
	}

}



 ?>